<template>
  <div class="item-content" v-loading="loading" :element-loading-text="$t('unit.loading')">
    <echarts class="echarts" ref="echarts" :option="echartsOption" />
  </div>
</template>
<script>
import Echarts from '@/components/Echarts';
import { InHistoryStats } from '@/api';
import lang from '@/lang';
import { mapGetters } from 'vuex';
import suanLiEchartsOptions from './suanLiEchartsOptions';

export default {
  name: 'statisticsEcharts',
  props: {
    coin_type: {
      type: String,
      default: '',
    },
  },
  components: {
    Echarts,
  },
  data() {
    return {
      loading: false,
      echartsOption: JSON.parse(JSON.stringify(suanLiEchartsOptions)),
      timer: undefined,
    };
  },
  computed: {
    ...mapGetters(['language']),
    coinHashUnit() {
      return this.coin_type === 'zec' ? 'Sol' : 'H';
    },
  },
  created() {
    this.getInHistoryStats();
    this.timer = window.setInterval(() => {
      this.getInHistoryStats();
    }, 15000);
  },
  beforeDestroy() {
    window.clearInterval(this.timer);
  },
  methods: {
    toggleEchartsLang() {
      this.echartsOption.legend.data[0] = lang.t('home.force');
      this.echartsOption.yAxis[0].name = lang.t('home.force');
      this.echartsOption.series[0].name = lang.t('home.force');
      if (this.$refs.echarts) {
        this.$refs.echarts.setOption(this.echartsOption);
      }
    },
    getInHistoryStats() {
      if (this.loading) {
        return;
      }
      this.loading = true;
      InHistoryStats({ coin_type: this.coin_type }).then((res) => {
        if (res.data.status === 1) {
          const d = res.data.data;
          const unit = d.unit;
          const data = d.data;
          const xData = [];
          const yData = [];
          Object.keys(data).sort().forEach((date) => {
            yData.push(data[date]);
            xData.push(date);
          });
          this.echartsOption.xAxis.data = xData;
          this.echartsOption.yAxis[0].name = `${lang.t('home.force')}(${
            unit
          }${this.coinHashUnit}/s)`;
          this.echartsOption.series[0].data = yData;
          this.echartsOption.tooltip.formatter = v => `${lang.t('statistics.time')}：${v[0].axisValue}<br/>${
            v[0].marker
          } ${lang.t('home.force')}：${v[0].data} ${unit}${this.coinHashUnit}/s`;
          this.echartsOption.xAxis.axisLabel.formatter = (v) => {
            const arr = v.split(' ');
            return arr[1] ? `${arr[0]}\n${arr[1]}` : arr[0];
          };
          if (this.$refs.echarts) {
            this.$refs.echarts.setOption(this.echartsOption);
          }
        }
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
  },
  watch: {
    language: {
      handler() {
        this.toggleEchartsLang();
      },
      immediate: true,
    },
  },
};
</script>

